package com.wise.service.portal.content.websuccessarticle;

import cn.hutool.core.bean.BeanUtil;
import com.wise.entities.content.Article;
import com.wise.entities.content.ArticleStatus;
import com.wise.entities.content.SuccessArticle;
import com.wise.framework.dao.SqlSelect;
import com.wise.framework.daomodel.DaoList;
import com.wise.framework.exception.LogicException;
import com.wise.summer.v1.portal.content.websuccessarticle.GetWebSuccessArticleById;
import org.springframework.stereotype.Service;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.util.List;

import static com.wise.model.content.ContentErrMsgs.Err_001600250017;
import static com.wise.model.content.ContentErrMsgs.Err_003600250007;

@Service
@SummerService
public class GetWebSuccessArticleByIdService implements SummerServiceBean<GetWebSuccessArticleById> {

    @Override
    public void sum(GetWebSuccessArticleById summer) {
        List<SuccessArticle> articles = getArticleList(summer);
        if (articles.isEmpty()) {
            throw new LogicException(this.getClass(), Err_003600250007);
        }
        GetWebSuccessArticleById.Result articleResult = new GetWebSuccessArticleById.Result();
        if (articles.get(0).getState() != null) {
            if (articles.get(0).getState().equals(ArticleStatus.NOTPUBLISH.value())) {
                throw new LogicException(this.getClass(), Err_001600250017);
            } else {
                BeanUtil.copyProperties(articles.get(0), articleResult);
                summer.setSummerResult(articleResult);
            }
        } else {
            BeanUtil.copyProperties(articles.get(0), articleResult);
            summer.setSummerResult(articleResult);
        }
    }

    /**
     * 获取查询列表
     *
     * @param model 入参
     * @return 列表
     */
    private List<SuccessArticle> getArticleList(GetWebSuccessArticleById model) {
        SqlSelect selectByAlias = SqlSelect.selec("*").fromClassName(SuccessArticle.class)
                .eq(Article.ALIAS, model.getId());
        List<SuccessArticle> articleList = DaoList.s(SuccessArticle.class, selectByAlias);
        // 如果根据别名查不到，则根据id查询
        if (articleList.isEmpty()) {
            SqlSelect selectArticle = SqlSelect.selec("*").fromClassName(SuccessArticle.class)
                    .eq(Article._id, model.getId());
            return DaoList.s(SuccessArticle.class, selectArticle);
        } else {
            return articleList;
        }
    }
}
